package it.afs.worklog.application.form;

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.ListModel;
import it.afs.worklog.Cliente;
import it.afs.worklog.Commessa;
import it.afs.worklog.User;
import it.afs.worklog.application.LoggedPage;

/**
 * @author Fanta
 */
public final class ReportPage extends LoggedPage
{
	private Form<Void> form;
	private ClienteDropDownChoice cliente;
	private CommessaDropDownChoice commessa;
	private UtenteDropDownChoice utente;
	private DropDownChoice<String> sort;
	private ShortDateTextField d1, d2;
	
	public ReportPage()
	{
		super();
		addComponents();
	}

	@Override
	protected void addComponents()
	{
		super.addComponents();
		
		add(getHomePageLink());
		
		form = new Form<Void>("form")
		{
			
			protected void onSubmit()
			{
				
				getFactory().getDao().getReport(d1.getModelObject(), d2.getModelObject(), utente.getModelObject(), commessa.getModelObject(), sort.getModelObject().substring(0, 1));
				
			};
		};
		add(form);
		
		cliente = new ClienteDropDownChoice("cliente", new Model<Cliente>(), new ListModel<Cliente>(getFactory().getDao().getClienti()));
		cliente.add(new AjaxFormComponentUpdatingBehavior("onchange")
		{
			
			@Override
			protected void onUpdate(AjaxRequestTarget target)
			{
				target.addComponent(commessa);
			}
		});
		form.add(cliente);
		
		LoadableDetachableModel<List<Commessa>> commesseModel = new LoadableDetachableModel<List<Commessa>>()
		{
			private static final long serialVersionUID = -2455723151177396489L;

			@Override
			protected List<Commessa> load()
			{
				if(cliente.getModelObject() != null)
				{
					return getFactory().getDao().getCommesse(cliente.getModelObject());
				}
				else
				{
					return Collections.emptyList();
				}
			}
		};
		
		commessa = new CommessaDropDownChoice("commessa", new Model<Commessa>(), commesseModel);
		commessa.setOutputMarkupId(true);
		form.add(commessa);
		
		utente = new UtenteDropDownChoice("user", new Model<User>(), getFactory().getDao().getUtenti());
		form.add(utente);
		
		form.add(d1 = new ShortDateTextField("d1", new Model<Date>()));
		form.add(d2 = new ShortDateTextField("d2", new Model<Date>()));
		
		sort = new DropDownChoice<String>("sort", new Model<String>("0 = data"), Arrays.asList(new String[]{"0 = data", "1 = utente", "2 = commessa"}));
		sort.setNullValid(false);
		form.add(sort);
		
		form.add(new FeedbackPanel("feedback"));
	}
}